package com.shxc.smarttrade.account.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.ChartTouchListener;
import com.github.mikephil.charting.listener.OnChartGestureListener;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.account.activity.AccountSettingActivity;
import com.shxc.smarttrade.account.activity.SettingActivity;
import com.shxc.smarttrade.account.activity.TradingAccountActivity;
import com.shxc.smarttrade.account.model.UserUserInfoModel;
import com.shxc.smarttrade.base.BaseFragment;
import com.shxc.smarttrade.dialogactivity.ChangeAccDialogActivity;
import com.shxc.smarttrade.index.activity.MessageCenterActivity;
import com.shxc.smarttrade.index.model.EAInfoModel;
import com.shxc.smarttrade.index.model.MessageHavingModel;
import com.shxc.smarttrade.info.Contents;
import com.shxc.smarttrade.kvb.activity.KvbNoticeActivity;
import com.shxc.smarttrade.main.MainActivity;
import com.shxc.smarttrade.old.activity.AlphaActivity;
import com.shxc.smarttrade.old.activity.SelectBrokeOpenAccountActivity;
import com.shxc.smarttrade.old.myview.MyMarkerView;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisModel;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisUtils;
import com.shxc.smarttrade.tigerwit.activity.TigerWitNoticeActivity;
import com.shxc.smarttrade.utils.Loger;
import com.shxc.smarttrade.utils.MyOkHttpUtils;
import com.shxc.smarttrade.utils.ToastUtils;

import org.xchris.view.annotation.ContentView;
import org.xchris.view.annotation.Event;
import org.xchris.view.annotation.ViewInject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 账户
 */
@ContentView(R.layout.fragment_account)
public class AccountFragment extends BaseFragment implements OnChartGestureListener, OnChartValueSelectedListener {

    @ViewInject(R.id.swiperefreshlayout)
    SwipeRefreshLayout swiperefreshlayout;//刷新
    @ViewInject(R.id.scrollview)
    ScrollView scrollview;//

    //顶部信息
    @ViewInject(R.id.message_red_imageview)
    ImageView message_red_imageview;//红点
    @ViewInject(R.id.head_imageview)
    ImageView head_imageview;//头像
    @ViewInject(R.id.nick_textview)
    TextView nick_textview;//
    @ViewInject(R.id.email_textview)
    TextView email_textview;//
    @ViewInject(R.id.account_textview)
    TextView account_textview;//
    @ViewInject(R.id.go_textview)
    TextView go_textview;//


    @ViewInject(R.id.networth_textview)
    TextView networth_textview;//账户净值
    @ViewInject(R.id.brokers_icon_imageview)
    ImageView brokers_icon_imageview;//经纪商icon
    @ViewInject(R.id.brokers_name_textview)
    TextView brokers_name_textview;//经纪商名称
    @ViewInject(R.id.timecount_view)
    View timecount_view;//模拟账户倒计时
    @ViewInject(R.id.timecount_textview)
    TextView timecount_textview;//模拟账户过期时间

    //交易数据
    @ViewInject(R.id.sourse_textview)
    TextView sourse_textview;//数据来源
    @ViewInject(R.id.total_profit_textview)
    TextView total_profit_textview;//总收益
    @ViewInject(R.id.profit_rate_textview)
    TextView profit_rate_textview;//收益率
    @ViewInject(R.id.total_hands_textview)
    TextView total_hands_textview;//总交易手数
    @ViewInject(R.id.total_times_textview)
    TextView total_times_textview;//总交易笔数
    @ViewInject(R.id.profit_times_textview)
    TextView profit_times_textview;//盈利订单
    @ViewInject(R.id.loss_times_textview)
    TextView loss_times_textview;//亏损订单

    //EA信息
    @ViewInject(R.id.seven_profit_textview)
    TextView seven_profit_textview;//七日收益
    @ViewInject(R.id.all_profit_textview)
    TextView all_profit_textview;//总收益
    @ViewInject(R.id.accuracy_rate_textview)
    TextView accuracy_rate_textview;//准确率
    @ViewInject(R.id.average_textview)
    TextView average_textview;//日均交易

    @ViewInject(R.id.linechart)
    LineChart linechart;//收益盈亏趋势

    private YAxis leftAxis;
    private String[] month = new String[5];
    private int eaId = -1;

    MainActivity mainActivity;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();

        swiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                update();
            }
        });
        mainActivity = (MainActivity) getActivity();

    }

    @Override
    public void onResume() {
        super.onResume();
        email_textview.setText(spImp.getEmail());
        if (spImp.getAccStatus() > 1) {
            go_textview.setVisibility(View.VISIBLE);
        } else {
            go_textview.setVisibility(View.GONE);
        }
        glideUtils.showCircle(spImp.getHeadUrl(), head_imageview);
        nick_textview.setText(spImp.getNick());
        update();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            update();
        }
    }

    long exitTime = 0;

    private void update() {
        if ((System.currentTimeMillis() - exitTime) > 1000) {
            exitTime = System.currentTimeMillis();
        } else {
            swiperefreshlayout.setRefreshing(false);
            return;
        }
        userinfo();
        eainfo();
        msghavemsg();
    }

    @Event({R.id.setting_imageview, R.id.message_view, R.id.info_view, R.id.account_view, R.id.go_textview, R.id.ea_view})
    private void onClick(View view) {
        switch (view.getId()) {
            case R.id.setting_imageview:
                //设置
                mainActivity.jumpType = 2;
                JumpTo(SettingActivity.class);
                break;
            case R.id.message_view:
                //消息
                mainActivity.jumpType = 2;
                JumpTo(MessageCenterActivity.class);
                break;
            case R.id.info_view:
                //编辑个人信息
                mainActivity.jumpType = 2;
                JumpTo(AccountSettingActivity.class);
                break;
            case R.id.account_view:
                //账户
                mainActivity.jumpType = 2;
                if (spImp.getAccStatus() > 1) {
                    //切换账户
                    JumpTo(TradingAccountActivity.class);//新
//                    JumpTo(TradeAccountActivity.class);//旧
                } else {
                    //开设真实账户
                    JumpTo(SelectBrokeOpenAccountActivity.class);//旧
                }
                break;
            case R.id.go_textview:
                //前往经纪商
                if (spImp.getAccType() == 0) {
                    mainActivity.jumpType = 1;
                    JumpTo(ChangeAccDialogActivity.class);
                } else if (spImp.getAccType() == 1) {
                    //TigerWit
                    mainActivity.jumpType = 2;
                    JumpTo(TigerWitNoticeActivity.class);
                } else if (spImp.getAccType() == 2) {
                    //KVB
                    mainActivity.jumpType = 2;
                    JumpTo(KvbNoticeActivity.class);
                }
                break;
            case R.id.ea_view:
                //EA详情
                mainActivity.jumpType = 2;
                Intent intent = new Intent(getActivity(), AlphaActivity.class);
                if (eaId == -1) {
                    ToastUtils.showToast("数据错误");
                    return;
                }
                intent.putExtra("eaId", eaId);
                startActivity(intent);
                break;
        }
    }

    //是否还有未读消息
    private void msghavemsg() {

        Map<String, Object> map = new HashMap<>();
        map.put("userId", spImp.getUserId());

        MyOkHttpUtils.getServiceDatas(map, Contents.MSG_HAVEMSG, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                Loger.e("response", response);
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, MessageHavingModel.class);
                    if (jam.isSuccess()) {
                        MessageHavingModel model = (MessageHavingModel) jam.getData();
                        if (model.getData().isHaveMsg()) {
                            message_red_imageview.setVisibility(View.VISIBLE);
                        } else {
                            message_red_imageview.setVisibility(View.GONE);
                        }

                    } else {
                        Loger.e("error_msg", jam.getMsg());
//                        ToastUtils.showToast(jam.getMsg());
                    }
                }
                swiperefreshlayout.setRefreshing(false);
            }

            @Override
            public void faild(Call call, Exception e, int id) {
                swiperefreshlayout.setRefreshing(false);
            }
        });

    }

    //用户信息
    private void userinfo() {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", spImp.getUserId());

        MyOkHttpUtils.getServiceDatas(map, Contents.USER_USERINFO, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                Loger.e("response", response);
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, UserUserInfoModel.class);
                    if (jam.isSuccess()) {
                        UserUserInfoModel model = (UserUserInfoModel) jam.getData();
                        setUi(model.getData());
                    } else {
                        Loger.e("error_msg", jam.getMsg());
//                        ToastUtils.showToast(jam.getMsg());
                    }
                }
                swiperefreshlayout.setRefreshing(false);
            }

            @Override
            public void faild(Call call, Exception e, int id) {
                swiperefreshlayout.setRefreshing(false);
            }
        });
    }

    //EA详情
    private void eainfo() {

        MyOkHttpUtils.getServiceDatas(null, Contents.EAINFO, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                Loger.e("response", response);
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, EAInfoModel.class);
                    if (jam.isSuccess()) {
                        EAInfoModel model = (EAInfoModel) jam.getData();
                        setEaInfo(model.getData().get(0));
                    } else {
                        Loger.e("info_error", jam.getMsg());
//                        ToastUtils.showToast(jam.getMsg());
                    }
                }
                swiperefreshlayout.setRefreshing(false);
            }

            @Override
            public void faild(Call call, Exception e, int id) {
                swiperefreshlayout.setRefreshing(false);
            }
        });
    }

    //填充UI数据
    public void setUi(UserUserInfoModel.DataBean model) {

        spImp.setHeadUrl(model.getHeadUrl());
        glideUtils.showCircle(spImp.getHeadUrl(), head_imageview);
        spImp.setNick(model.getNick());
        nick_textview.setText(spImp.getNick());

        //是否开户 - 账户数量
        spImp.setAccStatus(model.getAccStatus());

        if (model.getAccStatus() > 1) {
            account_textview.setText("切换账户");
            go_textview.setVisibility(View.VISIBLE);
        } else {
            account_textview.setText("开设真实账户");
            go_textview.setVisibility(View.GONE);
        }

        //当前账户
        spImp.setAccType(model.getAccType());
        switch (model.getAccType()) {
            case 0:
                brokers_icon_imageview.setImageResource(R.mipmap.st_logo_white);
                brokers_name_textview.setText("SmartTrade（模拟账户）");
                sourse_textview.setText("SmartTrade（模拟账户）的交易数据");
                timecount_view.setVisibility(View.VISIBLE);
                break;
            case 1:
                brokers_icon_imageview.setImageResource(R.mipmap.tw_head);
                brokers_name_textview.setText("TigerWit(" + model.getMt4Id() + ")");
                sourse_textview.setText("TigerWit 的交易数据");
                timecount_view.setVisibility(View.GONE);
                break;
            case 2:
                brokers_icon_imageview.setImageResource(R.mipmap.account_kvb_logo);
                brokers_name_textview.setText("KVB(" + model.getMt4Id() + ")");
                sourse_textview.setText("KVB 的交易数据");
                timecount_view.setVisibility(View.GONE);
                break;
        }
        //账号是否过期
        if (model.getDestroyDay() < 0) {
            timecount_textview.setText("已过期");
        } else if (model.getDestroyDay() == 0) {
            timecount_textview.setText("即将过期");
        } else {
            timecount_textview.setText(model.getDestroyDay() + "天后到期");
        }
        //账户净值
        networth_textview.setText(dealSymbol(model.getEquity()));
        //总收益
        total_profit_textview.setText(dealSymbol(model.getProfitCount()));
        //收益率
        profit_rate_textview.setText(getDigitsData(model.getYieldRate(), 2) + "%");
        //总交易手数
        total_hands_textview.setText(getDigitsData(model.getTotalVolume(), 2) + "手");
        //总交易笔数
        total_times_textview.setText(model.getTotalCount() + "笔");
        //盈利订单
        profit_times_textview.setText(model.getProfitCount() + "笔");
        //亏损订单
        loss_times_textview.setText(model.getLossTrade() + "笔");
        //收益盈亏趋势
        double max = 0;
        double min = 0;
        for (int i = 0; i < model.getProfitMonth().getMonth().size(); i++) {
            month[i] = model.getProfitMonth().getMonth().get(i) + "月";
            if (model.getProfitMonth().getProfit().get(i) > max)
                max = model.getProfitMonth().getProfit().get(i);
            if (model.getProfitMonth().getProfit().get(i) < min)
                min = model.getProfitMonth().getProfit().get(i);

        }

        float space = (float) ((max - min) / 4);
        if (space == 0)
            space = 5;
        if (max <= 0)
            leftAxis.setAxisMaximum(5f);
        else
            leftAxis.setAxisMaximum((float) max + 20);
        if (min >= 0)
            leftAxis.setAxisMinimum(-5f);
        else
            leftAxis.setAxisMinimum((float) min - 20);
        leftAxis.setDrawLimitLinesBehindData(true);

        setData(5, space, leftAxis, model.getProfitMonth().getProfit());
    }

    //设置EaInfo
    public void setEaInfo(EAInfoModel.DataBean model) {
        eaId = model.getId();
        //准确率
        accuracy_rate_textview.setText(BaseUtils.getDigitsData(model.getPrecisionRate(), 2) + "%");
        //日均交易
        average_textview.setText(model.getDayCount() + "笔");
        //七日收益
        seven_profit_textview.setText(BaseUtils.getDigitsData(model.getWeekYieldRate(), 2) + "%");
        //总收益
        all_profit_textview.setText(BaseUtils.getDigitsData(model.getProfitRateCount(), 2) + "%");
    }

    /**
     * 处理美元符号与正负号的
     *
     * @param result
     * @return
     */
    public static String dealSymbol(double result) {
        if (result < 0) {
            return "-$" + getDigitsData(Math.abs(result), 2);
        } else if (result == 0) {
            return "$" + getDigitsData(result, 2);
        } else {
            return "$" + getDigitsData(result, 2);
        }
    }

    /**
     * 格式化数据
     *
     * @param price
     * @param digits
     * @return
     */
    public static String getDigitsData(double price, int digits) {
        StringBuilder builder = new StringBuilder();
        builder.append("0.0");
        for (int i = 0; i < digits - 1; i++) {
            builder.append("0");
        }
        DecimalFormat decimalFormatter = new DecimalFormat(builder.toString());

        return decimalFormatter.format(price);

    }


    private void initView() {
        linechart.setOnChartGestureListener(this);
        linechart.setOnChartValueSelectedListener(this);
        linechart.setDrawGridBackground(false);
        linechart.getDescription().setEnabled(false);
        linechart.setTouchEnabled(true);
        linechart.setDragEnabled(true);
        linechart.setScaleEnabled(false);
        linechart.setPinchZoom(false);
        MyMarkerView mv = new MyMarkerView(getActivity(), R.layout.custom_marker_view);
        mv.setChartView(linechart); // For bounds control
        linechart.setMarker(mv);

        XAxis xAxis = linechart.getXAxis();
        xAxis.enableGridDashedLine(10f, 10f, 0f);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setLabelCount(5, true);

        leftAxis = linechart.getAxisLeft();
        leftAxis.setDrawAxisLine(false);
        leftAxis.removeAllLimitLines(); // reset all limit lines to avoid overlapping lines
        leftAxis.enableGridDashedLine(10f, 10f, 0f);
        leftAxis.setDrawZeroLine(false);

        linechart.getAxisRight().setEnabled(false);
        linechart.animateX(1000);

        Legend l = linechart.getLegend();
        l.setEnabled(false);
    }

    private void setData(int count, float range, YAxis yAxis, List<Double> datas) {

        ArrayList<Entry> values = new ArrayList<Entry>();

        for (int i = 0; i < count; i++) {

            float val = datas.get(i).floatValue();
            values.add(new Entry(i, val, getResources().getDrawable(R.drawable.red_circle)));//第二个参数为每个月的值（即百分比）
        }

        LineDataSet set1;

        if (linechart.getData() != null &&
                linechart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) linechart.getData().getDataSetByIndex(0);
            set1.setValues(values);
            linechart.getData().notifyDataChanged();
            linechart.notifyDataSetChanged();
        } else {
            // create a dataset and give it a type
            set1 = new LineDataSet(values, "");

            set1.setDrawIcons(false);

            // set the line to be drawn like this "- - - - - -"
            set1.enableDashedLine(10f, 5f, 0f);
            set1.enableDashedHighlightLine(10f, 5f, 0f);
            set1.setColor(Color.parseColor("#ff6200"));
            set1.setCircleColor(Color.parseColor("#ff6200"));
            set1.setLineWidth(1f);
            set1.setCircleRadius(3f);
            set1.setDrawCircleHole(false);
            set1.setValueTextSize(9f);
            set1.setDrawFilled(true);
            set1.setFormLineWidth(1f);
            set1.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
            set1.setFormSize(15.f);

            set1.setFillColor(Color.WHITE);
            set1.setDrawValues(false);

            ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
            dataSets.add(set1); // add the datasets

            // create a data object with the datasets
            LineData data = new LineData(dataSets);

            linechart.getXAxis().setValueFormatter(new IAxisValueFormatter() {
                @Override
                public String getFormattedValue(float value, AxisBase axis) {
                    return month[(int) value];
                }
            });

            // set data
            linechart.setData(data);
        }
    }

    @Override
    public void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {

    }

    @Override
    public void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {

    }

    @Override
    public void onChartLongPressed(MotionEvent me) {

    }

    @Override
    public void onChartDoubleTapped(MotionEvent me) {

    }

    @Override
    public void onChartSingleTapped(MotionEvent me) {

    }

    @Override
    public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) {

    }

    @Override
    public void onChartScale(MotionEvent me, float scaleX, float scaleY) {

    }

    @Override
    public void onChartTranslate(MotionEvent me, float dX, float dY) {

    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }

    public void JumpTo(Class cla) {
        Intent intent = new Intent(getActivity(), cla);
        startActivity(intent);
    }


}
